/**
  ******************************************************************************
  * @file           : device.c
  * @brief          : device
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 IOT Inn.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
  
#include "device.h"
  

static DeviceCTX_t devices[DEVICE_ID_MAX];  // 设备数组
static int device_count = 0;

// 注册设备
int device_register(DeviceCTX_t * dev) {
    if (dev->id >= DEVICE_ID_MAX) {
        return -1;  // 设备ID无效
    }
    devices[device_count++] = *dev;
    return 0;
}

// 查找设备
DeviceCTX_t * device_find(E_DeviceID_t id) {
    for (int i = 0; i < device_count; i++) {
        if (devices[i].id == id) {
            return &devices[i];
        }
    }
    return NULL;
}

// 初始化设备
int device_init(E_DeviceID_t id) {
    DeviceCTX_t * dev = device_find(id);
    if (dev && dev->ops->init) {
        return dev->ops->init(dev->priv);
    }
    return -1;
}

// 读取设备数据
int device_read(E_DeviceID_t id, void* buffer, uint32_t size) {
    DeviceCTX_t * dev = device_find(id);
    if (dev && dev->ops->read) {
        return dev->ops->read(dev->priv, buffer, size);
    }
    return -1;
}

// 写入设备数据
int device_write(E_DeviceID_t id, const void* buffer, uint32_t size) {
    DeviceCTX_t * dev = device_find(id);
    if (dev && dev->ops->write) {
        return dev->ops->write(dev->priv, buffer, size);
    }
    return -1;
}

// 控制设备
int device_control(E_DeviceID_t id, int cmd, void* arg) {
    DeviceCTX_t * dev = device_find(id);
    if (dev && dev->ops->control) {
        return dev->ops->control(dev->priv, cmd, arg);
    }
    return -1;
}

